<template>
    <Cascader :value="value" :data="data" :level="level" :load-data="loadArea" :change-on-select="changeOnSelect" clearable @on-change="handleChange" />
</template>

<script>
export default {
    name: "AreaCascader",
    props: {
        level: {
            type: Number,
            default: 3
        },
        value: {
            type: Array,
            default: function() {
                return [];
            }
        },
        changeOnSelect: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            data: []
        };
    },
    methods: {
        handleGetData(id) {
            return new Promise((resolve, reject) => {
                this.$ajax.post('/areaApi/get_children', {id: id}).then((res) => {
                    resolve(res.map(item => {
                        let obj = {
                            label: item.name,
                            value: item.id
                        }
                        if(parseInt(item.level_type) !== this.level) {
                            obj.children = [];
                            obj.loading = false;
                        }
                        return obj;
                    }))
                }).catch((err) => {
                    reject(err);
                })
            })
        },
        async loadArea(item, callback) {
            item.loading = true;
            await this.handleGetData(item.value).then(res => {
                item.children = res;
            }).catch(() => {
                // todo
            })
            callback();
            item.loading = false;
        },
        handleChange(value) {
            this.$emit('input', value);
        }
    },
    mounted() {
        this.handleGetData(100000).then(res => {
            this.data = res;
        }).catch((err) => {
            // todo
        })
    }
}
</script>